package com.lyh.hkcloud.module.m1300025;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.activity.HomeActivity;
import com.lyh.hkcloud.adapter.AutoCompleteTextViewAdapter;
import com.lyh.hkcloud.base.BaseActivity;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.m1300025.adapter.ListViewAdapter;
import com.lyh.hkcloud.module.m1300084.service.Service;
import com.lyh.hkcloud.util.base.JsonUtil;
import com.lyh.hkcloud.util.base.SaveData;
import com.lyh.hkcloud.util.base.StringUtils;
import com.lyh.hkcloud.util.base.ToastUtils;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zhongfan
 * @program: hkCloud
 * @description:创建单据
 * @company—date: 利元数据 2022-02-16 10:04
 **/
public class IndexActivity extends BaseActivity implements View.OnClickListener, ListViewAdapter.DeleteCallback {

    private ImageView go_back;
    private AutoCompleteTextView atv_company;
    private AutoCompleteTextView atv_department;
    private AutoCompleteTextView atv_fa_type;
    private AutoCompleteTextView atv_ma_type;
    private AutoCompleteTextView atv_core;
    private AutoCompleteTextView atv_location_number;
    private Button bt_cancel;
    private Button bt_save;

    private Service service;

    Map<String, Object> inMap = new HashMap<>();
    //公司信息
    List<String>companyArray=new ArrayList<>();
    //部门信息
    List<String>departmentArray=new ArrayList<>();
    /*查询位置信息*/
    List<String> locationArray;
    /*查询成本中心*/
    List<String> costArray;
    //物料类型
    List<String> materialArray;
    //资产类型
    List<String> faTypeArray;
    @Override
    public void onClick(View v) {

    }

    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_1300025;
    }

    @Override
    protected int getSubmitResId() {
        return R.id.bt_save;
    }

    @Override
    protected int getClearResId() {
        return R.id.bt_cancel;
    }

    @Override
    protected void initView() {
        go_back = findViewById(R.id.go_back);
        atv_company = findViewById(R.id.atv_company);
        atv_department = findViewById(R.id.atv_department);
        atv_core = findViewById(R.id.atv_core);
        atv_location_number = findViewById(R.id.atv_location_number);
        atv_ma_type = findViewById(R.id.atv_ma_type);
        atv_fa_type = findViewById(R.id.atv_fa_type);
        bt_cancel = findViewById(R.id.bt_cancel);
        bt_save = findViewById(R.id.bt_save);
        getSupportActionBar().hide();
    }

    @Override
    protected void initEvent() {

        go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndexActivity.this, HomeActivity.class);
                IndexActivity.this.startActivity(intent);
            }
        });
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndexActivity.this, HomeActivity.class);
                IndexActivity.this.startActivity(intent);
            }
        });
    }

    @Override
    public void deletePosition(int saveposition) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //查询 位置编号、成本中心 下拉数据
        this.querySpinner();
    }

    @Override
    protected void onBeginInit() {
        service = new Service(IndexActivity.this);
    }

    @Override
    protected void onSubmit() {
        this.createInventory();
    }

    /**
     * 给下拉框赋值
     *
     * @param starArray            数据集合
     * @param spinner              下拉框
     * @param specifyDefaultValues 默认选中值
     *                             key 	 盘点创建接口入参map的key
     * @return void
     * @author: 黄斌成
     * @Date 2022/2/18 14:34
     **/
    private void initSpinner(List<String> starArray, Spinner spinner, String specifyDefaultValues, String keyName,String keyCode) {

        starArray.add(0, BusinessConstants.PLEASE_SELECT);

        //声明一个下拉列表的数组适配器
        ArrayAdapter<String> starAdapter = new ArrayAdapter<>(IndexActivity.this, R.layout.item_select, starArray);

        //设置数组适配器的布局样式
        starAdapter.setDropDownViewResource(R.layout.item_dropdown);

        //设置下拉框的标题，不设置就没有难看的标题了
        spinner.setPrompt("请选择行星");
        //设置下拉框的数组适配器
        spinner.setAdapter(starAdapter);
        //设置下拉框默认的显示第一项
        if (StringUtils.isNotEmpty(specifyDefaultValues) && starArray.indexOf(specifyDefaultValues) != -1) {
            spinner.setSelection(starArray.indexOf(specifyDefaultValues));
        } else {
            spinner.setSelection(0);
        }
        starArray.indexOf(specifyDefaultValues);
        spinner.setSelection(0);
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
        spinner.setOnItemSelectedListener(new MySelectedListener(starArray, keyName,keyCode));
        //Log.v("starArry", starArray.toString());
    }

    /**
     * 下拉框选择事件
     *
     * @author: zhongfan
     * @Date 2022/2/16 14:34
     **/
    class MySelectedListener implements AdapterView.OnItemSelectedListener {
        List<String> starArray;
        String key;
        String name;

        public MySelectedListener(List<String> starArray, String key,String name) {
            this.starArray = starArray;
            this.key = key;
            this.name = name;
        }

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            //位置代码
            String[] split = starArray.get(i).split(BusinessConstants.SEPARATOR);
            if (split != null && split.length == 2) {
                inMap.put(key, split[0]);
                inMap.put(name, split[1]);
            }else{
                inMap.put(key, starArray.get(i));
            }

            //Toast.makeText(IndexActivity.this, "您选择的是：" + "starArray[i]", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }

    /**
     * 查询 位置编号、成本中心 下拉数据
     *
     * @return void
     * @author: zhongfan
     * @Date 2022/2/15 21:00
     **/
    private void querySpinner() {

        /*查询位置信息*/
        locationArray = new ArrayList<>();
        service.post(new JSONObject(), HttpUrlComstants.QUERY_LOCATION_INFORMATION, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {
                    JSONArray centerinfo = JsonUtil.getJsonObjectArray(response, "locationinfo", IndexActivity.this);
                    for (int i = 0; i < centerinfo.length(); i++) {
                        if (centerinfo.get(i) == null) {
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject(centerinfo.get(i).toString());
                        if (jsonObject.get("location") == null) {
                            continue;
                        }
                        locationArray.add(jsonObject.get("location") + BusinessConstants.SEPARATOR + jsonObject.get("locationname"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //initSpinner(locationArray, sp_location_number, null, "location","location_name");
                setATVData(locationArray,atv_location_number);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });

        /*查询成本中心*/
        costArray = new ArrayList<>();
        service.post(new JSONObject(), HttpUrlComstants.QUERY_COST_CENTER, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                try {
                    JSONArray centerinfo = JsonUtil.getJsonObjectArray(response, "centerinfo", IndexActivity.this);
                    for (int i = 0; i < centerinfo.length(); i++) {
                        if (centerinfo.get(i) == null) {
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject(centerinfo.get(i).toString());
                        if (jsonObject.get("centername") == null) {
                            continue;
                        }
                        costArray.add(jsonObject.get("centercode") + BusinessConstants.SEPARATOR + jsonObject.get("centername"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //initSpinner(costArray, sp_core, null, "centercode","centername");
                setATVData(costArray,atv_core);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });

        //查询公司- level – #1=公司，2=中心，3=部门
        this.queryCompanyAndDeptment(companyArray,atv_company,"1","corpcode","corpname");

        //查询部门
        this.queryCompanyAndDeptment(departmentArray,atv_department,"3","hrorgunitcode","hrorgunitname");
//        查询物料类型信息
        this.queryMaterialType();

        //查询资产类型信息
        this.queryAssetType();
    }

    private void queryAssetType() {
        faTypeArray = new ArrayList<>();
        service.post(new JSONObject(), HttpUrlComstants.QUERY_FA_TYPE_INFO, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                try {
                    JSONArray matypeinfo = JsonUtil.getJsonObjectArray(response, "fatypeinfo", IndexActivity.this);
                    for (int i = 0; i < matypeinfo.length(); i++) {
                        if (matypeinfo.get(i) == null) {
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject(matypeinfo.get(i).toString());
                        if (jsonObject.get("fatypename") == null) {
                            continue;
                        }
                        faTypeArray.add(jsonObject.get("fatypecode") +BusinessConstants.SEPARATOR+ jsonObject.get("fatypename"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //initSpinner(faTypeList, sp_fa_type, null, "fatype","fatype_name");
                setATVData(faTypeArray,atv_fa_type);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void queryMaterialType() {
        materialArray = new ArrayList<>();
        service.post(new JSONObject(), HttpUrlComstants.QUERY_MA_TYPE_INFO, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                try {
                    JSONArray matypeinfo = JsonUtil.getJsonObjectArray(response, "matypeinfo", IndexActivity.this);
                    for (int i = 0; i < matypeinfo.length(); i++) {
                        if (matypeinfo.get(i) == null) {
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject(matypeinfo.get(i).toString());
                        if (jsonObject.get("matypename") == null) {
                            continue;
                        }
                        materialArray.add(jsonObject.get("matypecode") + BusinessConstants.SEPARATOR + jsonObject.get("matypename"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //initSpinner(materialType, sp_ma_type, null, "matype","matype_name");
                setATVData(materialArray,atv_ma_type);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * @param level   #1=公司，2=中心，3=部门
     * @param atv 下拉框组件
     * @param setKey  盘点创建接口入参map的key
     * @return
     * @Description 查询公司和部门
     * @Date 2022/2/19 20:52
     * @author 黄斌成
     **/

    private void queryCompanyAndDeptment(List<String> dataList,AutoCompleteTextView atv, String level, String setKey,String code) {
        //查询公司入参
        JSONObject inMap = new JSONObject();
        try {
            inMap.put("level", level);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        service.post(inMap, HttpUrlComstants.QUERY_DEPT_INFO, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                try {
                    JSONArray deptinfo = JsonUtil.getJsonObjectArray(response, "deptinfo", IndexActivity.this);
                    for (int i = 0; i < deptinfo.length(); i++) {
                        if (deptinfo.get(i) == null) {
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject(deptinfo.get(i).toString());
                        if (jsonObject.get("deptcode") == null) {
                            continue;
                        }
                        dataList.add(jsonObject.get("deptcode").toString() + BusinessConstants.SEPARATOR + jsonObject.get("deptname").toString());
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //initSpinner(dataList, spinner, null, setKey,code);
                setATVData(dataList,atv);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void setATVData(List<String>data,AutoCompleteTextView atc){
        AutoCompleteTextViewAdapter actvAdapter =new AutoCompleteTextViewAdapter(this, R.layout.item_select,data);
        atc.setAdapter(actvAdapter);
        atc.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                AutoCompleteTextView view = (AutoCompleteTextView) v;
                if (hasFocus) {
                    view.showDropDown();
                }
            }
        });
        atc.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AutoCompleteTextView view = (AutoCompleteTextView) v;
                view.showDropDown();
                return false;
            }
        });
    }

    /**
     * @param
     * @return
     * @Description 创建盘点单
     * @Date 2022/2/18 20:46
     * @author 黄斌成
     **/
    private void createInventory() {

        /*for (Object value : inMap.values()) {
            if (StringUtils.isEmpty(value.toString())) {
                ToastUtils.makeText(IndexActivity.this, "有未填写的信息", ToastUtils.LENGTH_SHORT).show();
                return;
            }
        }*/
        if(!companyArray.contains(atv_company.getText().toString())){
            Toast.makeText(com.lyh.hkcloud.module.m1300025.IndexActivity.this, "公司不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        inMap.put("corpcode",atv_company.getText().toString());

        if(!departmentArray.contains(atv_department.getText().toString())){
            Toast.makeText(com.lyh.hkcloud.module.m1300025.IndexActivity.this, "部门不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        inMap.put("hrorgunitcode",atv_department.getText().toString());

        if(!costArray.contains(atv_core.getText().toString())){
            Toast.makeText(com.lyh.hkcloud.module.m1300025.IndexActivity.this, "中心不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        inMap.put("centercode",atv_core.getText().toString());

        String location=atv_location_number.getText().toString();
        if(!locationArray.contains(location)){
            Toast.makeText(com.lyh.hkcloud.module.m1300025.IndexActivity.this, "位置编号不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] location1 = location.split(BusinessConstants.SEPARATOR);
        inMap.put("location", location1[0]);
        inMap.put("location_name", location1[1]);


        String matype=atv_ma_type.getText().toString();
        if(!materialArray.contains(atv_ma_type.getText().toString())){
            Toast.makeText(com.lyh.hkcloud.module.m1300025.IndexActivity.this, "物料编号不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] matype2 = matype.split(BusinessConstants.SEPARATOR);
        inMap.put("matype", matype2[0]);
        inMap.put("matype_name", matype2[1]);

        String fatype=atv_fa_type.getText().toString();
        if(!faTypeArray.contains(atv_fa_type.getText().toString())){
            Toast.makeText(com.lyh.hkcloud.module.m1300025.IndexActivity.this, "资产类别不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] fatype2 = fatype.split(BusinessConstants.SEPARATOR);
        inMap.put("fatype", fatype2[0]);
        inMap.put("fatype_name", fatype2[1]);

        bt_save.setEnabled(false);
        JSONObject maindata = new JSONObject();
        try {
            /**接口入参*/
            maindata.put("maindata", JsonUtil.toJSONObject(inMap));
            maindata.put("userid", SaveData.getString(this, "userid"));
            maindata.put("username", SaveData.getString(this, "userName"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        service.post(maindata, HttpUrlComstants.CREATE_INVENTORY, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                ToastUtils.makeText(IndexActivity.this, response.optString("message"), ToastUtils.LENGTH_SHORT).show();
                Intent intent = new Intent(IndexActivity.this, HomeActivity.class);
                IndexActivity.this.startActivity(intent);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
                bt_save.setEnabled(true);
            }
        });
    }
}
